package com.guoqi.keepsign.kb

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import com.google.gson.Gson
import com.guoqi.keepsign.IPConfig
import com.guoqi.keepsign.IPConfig.DEFAULT_TIMEOUT
import com.guoqi.keepsign.IPConfig.DEFUALT_USERAGENT
import com.guoqi.keepsign.R
import com.guoqi.keepsign.album.AlbumUI
import com.guoqi.keepsign.base.BaseFm
import com.guoqi.keepsign.base.CommonBean
import com.guoqi.keepsign.base.ImageInfo
import kotlinx.android.synthetic.main.fm_common.*
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.select.Elements
import java.util.*


class KbFm : BaseFm(), SwipeRefreshLayout.OnRefreshListener {

    private lateinit var url: String
    private var showType = 1
    private var mList: ArrayList<CommonBean>? = null
    private var mPage: Int? = 1
    private var mKbAdapter: KbAdapter? = null
    private var gm: GridLayoutManager? = null
    var imageList = ArrayList<ImageInfo>()

    companion object {

        fun newInstance(ip: String, showType: Int): KbFm {
            val fragment = KbFm()
            val bundle = Bundle()
            bundle.putString("ip", ip)
            bundle.putInt("showType", showType)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun initLayout(): Int {
        return R.layout.fm_common
    }

    override fun initUI() {
        url = arguments?.getString("ip") ?: ""
        showType = arguments?.getInt("showType") ?: 1
        mSwipeRefresh.setColorSchemeColors(Color.rgb(255, 64, 129))
        mSwipeRefresh.setOnRefreshListener(this)
        //lm = LinearLayoutManager(context)
        gm = GridLayoutManager(context, showType)
        mRvCommonList.layoutManager = gm
        mRvCommonList.setHasFixedSize(true)
        mList = ArrayList()
        mRvCommonList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            var lastVisibleItem: Int? = 0
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem!! + 1 == mKbAdapter?.itemCount) {
                    mKbAdapter?.changeMoreStatus(mKbAdapter?.LOAD_MORE!!)
                    mPage = mPage!! + 1
                    getData(mPage)
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val layoutManager = recyclerView?.layoutManager as LinearLayoutManager
                //最后一个可见的ITEM
                lastVisibleItem = layoutManager.findLastVisibleItemPosition()
            }
        })
        loading.visibility = View.VISIBLE
    }

    private fun getData(page: Int?) {

        Thread(Runnable {
            try {
                Log.e(TAG, "$url$page.html")
                val doc: Document = Jsoup.connect("$url$page.html")
                        .timeout(DEFAULT_TIMEOUT).userAgent(DEFUALT_USERAGENT).get()
                val imgSingle: Elements? = doc.getElementsByClass("newslist")
                val links = imgSingle?.select("dl dt a")
                links?.forEach {
                    mCommonBean = CommonBean(it.html(), it.attr("href"))
                    mList!!.add(mCommonBean!!)
                    Log.e(TAG, Gson().toJson(mCommonBean))
                }
                activity?.runOnUiThread {
                    mKbAdapter?.changeMoreStatus(mKbAdapter?.PULLUP_LOAD_MORE!!)
                    if (mPage != 1) {
                        mRvCommonList.adapter!!.notifyDataSetChanged()
                    } else {
                        mKbAdapter = KbAdapter(activity, mList)
                        mRvCommonList.adapter = mKbAdapter
                        mKbAdapter?.setOnTitleClickListener(object : KbAdapter.OnTitleClickListener {
                            override fun onTitleClick(title: String, picUrl: String) {
                                imageList.clear()
                                if (picUrl.contains("/html/")) {
                                    handlerKb(title, picUrl)
                                }
                            }

                        })
                    }
                    loading.visibility = View.GONE
                    ll_none.visibility = View.GONE
                }
            } catch (e: Exception) {
                activity?.runOnUiThread {
                    loading.visibility = View.GONE
                    mCommomAdapter?.changeMoreStatus(mCommomAdapter?.NO_LOAD_MORE!!)
                }
            }
        }).start()
    }

    override fun onRefresh() {
        mSwipeRefresh.isRefreshing = false
        getData(mPage)
    }

    override fun loadData() {
        if (mList!!.isEmpty())
            getData(mPage)
    }

    private fun handlerKb(title: String, picUrl: String) {
        // /html/kbxiazai/201904/27-42029.html
        loading.visibility = View.VISIBLE
        Thread(Runnable {
            try {
                Log.e(TAG, IPConfig.KB + picUrl)
                val doc: Document = Jsoup.connect(IPConfig.KB + picUrl).timeout(DEFAULT_TIMEOUT).userAgent(DEFUALT_USERAGENT).get()
                val eContent: Elements? = doc.getElementsByClass("content")
                val eImgs = eContent?.select("img")
                eImgs?.forEach {
                    imageList.add(ImageInfo(it.attr("src")))
                    Log.e(TAG, it.attr("src"))
                }
                activity?.runOnUiThread {
                    loading.visibility = View.GONE
                }
                val intent = Intent(activity, AlbumUI::class.java)
                intent.putExtra("title", title)
                intent.putExtra("imageList", imageList)
                activity?.startActivity(intent)
            } catch (e: Exception) {
                activity?.runOnUiThread {
                    loading.visibility = View.GONE
                    mCommomAdapter?.changeMoreStatus(mCommomAdapter?.NO_LOAD_MORE!!)
                }
            }
        }).start()
    }

}